package com.laohei.looping_stack.component

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.animateOffsetAsState
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.toMutableStateMap
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.util.fastForEachIndexed
import androidx.compose.ui.zIndex
import kotlinx.coroutines.launch

@Composable
fun LoopingStack(
    images: List<Int>,
    modifier: Modifier = Modifier,
    imageSize: DpSize = DpSize(200.dp, 200.dp),
    shape: Shape = RoundedCornerShape(20.dp),
    borderWidth: Dp = 5.dp,
    borderColor: Color = Color.White,
    degreesFactor: Float = 3.5f,
    scaleFactor: Float = 0.06f,
    contentScale: ContentScale = ContentScale.Crop
) {
    val zIndexMap = remember(images) {
        images.reversed().mapIndexed { index, item ->
            item to index
        }.toMutableStateMap()
    }
    val scope = rememberCoroutineScope()
    var currentIndex by remember { mutableIntStateOf(0) }
    var currentOffset by remember { mutableStateOf(Offset(0f, 0f)) }
    var isDragging by remember { mutableStateOf(false) }

    Box(modifier = modifier, contentAlignment = Alignment.Center) {
        images.fastForEachIndexed { index, item ->
            val zIndex = zIndexMap[item] ?: 0
            val rotation by animateFloatAsState(
                targetValue = (images.size - 1 - zIndex) * degreesFactor
            )
            val rotationAnimatable = if (currentIndex == index) {
                Animatable(initialValue = 0f)
            } else {
                null
            }
            val scale by animateFloatAsState(
                targetValue = 1 - (images.size - 1 - zIndex) * scaleFactor
            )
            val offset by animateOffsetAsState(
                targetValue = if (isDragging && index == currentIndex) currentOffset else Offset.Zero,
                finishedListener = {
                    scope.launch {
                        rotationAnimatable?.animateTo(
                            (images.size - 1 - zIndex) * degreesFactor
                        )
                    }
                }
            )

            Image(
                painter = painterResource(item),
                contentDescription = null,
                contentScale = contentScale,
                modifier = Modifier
                    .size(imageSize)
                    .graphicsLayer {
                        scaleX = scale
                        scaleY = scale
                        val isDragTarget = currentIndex == index
                        if (isDragTarget) {
                            translationX = offset.x
                            translationY = offset.y
                            rotationZ = if (isDragging) {
                                0f
                            } else {
                                rotationAnimatable!!.value
                            }
                        } else {
                            rotationZ = rotation
                        }
                        transformOrigin = TransformOrigin(1f, 1f)
                    }
                    .clip(shape)
                    .border(borderWidth, borderColor, shape)
                    .zIndex(zIndex.toFloat())
                    .pointerInput(Unit) {
                        detectDragGestures(
                            onDragStart = {
                                currentIndex = index
                                isDragging = true
                            },
                            onDrag = { _, dragOffset ->
                                currentOffset = currentOffset + dragOffset
                            },
                            onDragEnd = {
                                if (zIndexMap[images[currentIndex]] == images.size - 1) {
                                    zIndexMap.forEach { key, value ->
                                        zIndexMap[key] = (value + 1) % images.size
                                    }
                                }
                                isDragging = false
                                currentOffset = Offset.Zero
                            },
                            onDragCancel = {}
                        )
                    }
            )
        }
    }
}